using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using AjGenesisStudio.Properties;
using System.IO;

namespace AjGenesisStudio.Commands
{
    class OpenProjectCommand : Command
    {
        string dirpath;

        public override bool Execute()
        {
            if (ShowOpen())
            {
                OpenFolder();
            }
            return true;
        }

        public bool Execute(string path)
        {
            if (Directory.Exists(path))
            {
                dirpath = path;
                OpenFolder();
            }
            return true;
        }

        private bool ShowOpen()
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.Description = "Select directory to open.";
            if (!string.IsNullOrEmpty(Settings.Default.LastProject))
                if (Directory.Exists(Settings.Default.LastProject))
                    dlg.SelectedPath = Settings.Default.LastProject;

                
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                dirpath = dlg.SelectedPath;
                Settings.Default.LastProject = dirpath;
                return true;
            }
            else
            {
                return false;
            }
        }

        private void OpenFolder()
        {
            string project_name = Path.GetFileName(dirpath);

            Global.Instance.StartWork("Loading " + project_name);
            
            Global.Instance.MainForm.ShowProjectExplorer();
            Panels.ExplorerPanel.Instance.DirectoryPath = dirpath;

            AddRecentProject(dirpath);

            Global.Instance.MainForm.Text = project_name + " - AjGenesis Studio 0.2 b";

            Global.Instance.EndWork();
        }

        private void AddRecentProject(string value)
        {
            if (Settings.Default.RecentProjects == null)
                Settings.Default.RecentProjects = new System.Collections.Specialized.StringCollection();

            if (Settings.Default.RecentProjects.Contains(value))
                Settings.Default.RecentProjects.Remove(value);
        
            if (Settings.Default.RecentProjects.Count > 5)
            {
                for (int i = 0; i < Settings.Default.RecentProjects.Count - 1; i++)
                    Settings.Default.RecentProjects[i] = Settings.Default.RecentProjects[i + 1];
                Settings.Default.RecentProjects[4] = value;
            }
            else
                Settings.Default.RecentProjects.Add(value);
        }
    }
}
